﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebAPI_Demo.Models;
using WebAPI_Demo.Models.Database;
using WebAPI_Demo.Service;

namespace WebAPI_Demo.Controllers
{
    //路由
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        //注入jwt服务
        private readonly IJWTService _jwtService;
        //定义数据库上下文
        private readonly Store_2022Context _db;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="jwtService"></param>
        public AuthenticationController(IJWTService jwtService, Store_2022Context db)
        {
            _jwtService = jwtService;
            _db = db;
        }

        /// <summary>
        /// 创建token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string CreateToken(string name)
        {
            //返回  通过用户名    创建token
            return _jwtService.CreateToken(name,0);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //标签 接口需要授权
        [Authorize]
        public string UserInfo()
        {
            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            return Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;
        }

        /// <summary>
        /// 注册账号
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public string RegUser(JWTUser user)
        {
            var newuser = new User() {
                UserName = user.u_name,
                Password = user.u_pwd,
                Photo = user.u_photo,
                Desc = user.u_desc,
                CraeteTime = DateTime.Now
            };
            //获取用户操作
            var userList = _db.Users.AsQueryable();
            //查询用户存不存在
            var row = userList.Count(x => x.UserName == user.u_name);
            if (row > 0)
            {
                return "用户名存在，请修改！";
            }
            //数据库上下.操作的表名.操作的方法(参数)
            _db.Users.Add(newuser);
            row = _db.SaveChanges();
            if (row > 0)
            {
                return "注册成功";
            }
            else
            {
                return "注册失败";
            }

        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string LoginUser(string name,string pwd)
        {
            if (name == null || pwd == null)
            {
                return "有缺少项";
            }
            //获取用户操作
            var userList = _db.Users.AsQueryable();
            //查询用户存不存在
            var row = userList.Count(x => x.UserName == name && x.Password == pwd);
            if (row > 0)
            {
                var userid = _db.Users.FirstOrDefault(x => x.UserName == name).UserId;
                return "您的token：" + _jwtService.CreateToken(name, userid);
            }
            else
            {
                return "登录失败";
            }
        }

        /// <summary>
        /// 查询信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        //标签 接口需要授权
        [Authorize]
        public string ShowUser(string token)
        {
            //var row = Response.HttpContext.User.Claims.Count();
            //if (row <= 0)
            //{
            //    return "未授权！";
            //}
            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            var result = "您好：" + Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;
            result += " 编号：" + Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            return result;
        }
    }
}
